package _2025_3_17;

public class MyBlockingDeque {
    private int[]elem;
    public MyBlockingDeque(int space) {
        if(space<=0) {
            throw new RuntimeException();
        }
        else elem=new int[space];
    }
    private volatile int head=0;//头下标
    private volatile int tail=0;//尾下标
    private volatile int size=0;//数组有效个数

    public void put(int value) throws InterruptedException {
        synchronized (this) {
            if (size >= elem.length) {
                //阻塞，使其等待 this当前这个
                this.wait();
            }
            elem[tail] = value;
            tail++;
            if (tail == elem.length) {
                tail = 0;
            }
            size++;
        }
    }
    public synchronized Integer take() throws InterruptedException {
        if(size==0){
            this.wait();
        }
        Integer key=elem[head];
        head++;
        if(head==elem.length){
            head=0;
        }
        size--;
        //唤醒阻塞等待线程
            this.notifyAll();
        return key;
    }

}
